<?php

namespace App\Admin\Controllers;

use App\Exceptions\ApiException;
use App\Http\Controllers\Controller;
use App\Jobs\ReleaseUserFromGagList;
use App\Models\LogBalance;
use App\Models\Order;
use App\Models\Product;
use App\Models\Shop;
use App\Models\SysCity;
use App\Models\SysDistrict;
use App\Models\SysProvince;
use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\DB;

class ApiController extends Controller
{
    /**
     * 获取省数据
     *
     * @return mixed
     */
    public function province()
    {
        return SysProvince::get(['id', DB::raw('name as text')]);
    }

    /**
     * 获取市数据
     *
     * @param Request $request
     * @return mixed
     */
    public function city(Request $request)
    {
        $q = $request->get("q");

        return SysCity::where('province_id', $q)->get(['id', DB::raw('name as text')]);
    }

    /**
     * 获取区数据
     *
     * @param Request $request
     * @return mixed
     */
    public function district(Request $request)
    {
        $q = $request->get("q");

        return SysDistrict::where('city_id', $q)->get(['id', DB::raw('name as text')]);
    }

    /**
     * 冻结/解冻用户
     *
     * @param Request $request
     * @return array
     */
    public function setUserLoginStatus(Request $request)
    {
        $user = new User();

        $data = $user->find($request->get('id'));

        if ($data->login_status == User::FORBIDDEN) {
            $data->login_status = User::NORMAL;
        } else {
            $data->login_status = User::FORBIDDEN;
        }

        $res = $data->save();

        if ($res) {
            return ['message' => trans('admin.update_succeeded'), 'status' => true, 'label' => User::$LOGIN_STATUS_MAP[$data->login_status]];
        } else {
            return ['message' => trans('admin.failed'), 'status' => false, 'label' => User::$LOGIN_STATUS_MAP[$data->login_status]];
        }
    }

    /**
     * 禁言/解禁用户
     *
     * @param Request $request
     * @return array
     */
    public function setUserGagStatus(Request $request)
    {
        $user = new User();

        $data = $user->find($request->get('id'));
        $gag_duration = $request->input('gag_time');

        if ($data->gag_status == User::FORBIDDEN) {
            $data->gag_status = User::NORMAL;
            $data->gag_duration = null;

        } else {
            $data->gag_status = User::FORBIDDEN;
            $data->gag_duration = $gag_duration;

            if ($gag_duration) {
                $job = (new ReleaseUserFromGagList($data->id))
                    ->delay(Carbon::now()->addMinutes($gag_duration));

                dispatch($job);
            }

        }

        $res = $data->save();

        if ($res) {
            return ['message' => trans('admin.update_succeeded'), 'status' => true, 'label' => User::$GAG_STATUS_MAP[$data->gag_status]];
        } else {
            return ['message' => trans('admin.failed'), 'status' => false, 'label' => User::$GAG_STATUS_MAP[$data->gag_status]];
        }
    }

    /**
     * 设置推荐
     *
     * @param Request $request
     */
    public function setRecommend(Request $request)
    {
        $id = $request->get('id');

        $model = $request->get('model');

        if ($model === 'Shop') {
            $model = Shop::find($id);
        }

        if ($model === 'Product') {
            $model = Product::find($id);
        }

        $model->recommended = !$model->recommended;

        $model->save();

    }

    public function topUp(Request $request)
    {
        $id = $request->get('id');

        $amount = $request->get('amount');

        DB::transaction(function () use ($id, $amount) {
            try {
                $user = User::find($id);

                $user->wallet->balance += $amount;

                $user->push();

                //记录
                $log['user_id'] = $id;
                $log['user_balance'] = $user->wallet->balance;
                $log['action'] = LogBalance::TOP_UP;
                $log['amount'] = $amount;

                LogBalance::create($log);

            } catch ( \Exception $exception ) {
                throw new ApiException(trans('admin.top_up_failed'));
            }
        });

        return ['message' => trans('admin.top_up_succeed'), 'status' => true];
    }

    public function refund(Request $request)
    {
        $id = $request->get('id');

        DB::transaction(function () use ($id) {
            try {
                $order = Order::find($id);

                $order->refund_status = Order::REFUND_STATUS_SUCCESS;
                $order->refund_at = Carbon::now();

                $order->user->wallet->balance += $order->total_amount;

                $order->push();

            } catch ( \Exception $exception ) {
                throw new ApiException(trans('admin.refund_failed'));
            }
        });

        return ['message' => trans('admin.refund_succeed'), 'status' => true];
    }
}
